﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Net.Fan.SmallPig.DataAccess;
using Net.Fan.SmallPig.Common.DBMeta;
using Net.Fan.SmallPig.Common;

namespace Net.Fan.SmallPig.BusinessRules
{
    public class GroupBiz
    {
        public static DataTable GetAdministrators()
        {
            return GroupDA.GetGroupMembers("administrators").Tables[0];
        }

        /// <summary>
        /// Get a user's group and format to a string.
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static string GetGeneralGroupString(string userName)
        {
            string groups = string.Empty;
            DataTable dt = GroupDA.GetGeneralGroups(userName);
            string sp = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                groups += sp;
                groups += dr[GroupMeta.groupNameField].ToString();
                sp = ";";
            }
            return groups;
        }

        public static Result DelAdministrator(string adminName)
        {
            Result r = new Result();
            DataTable admin = GetAdministrators();
            if (admin.Rows.Count > 1)
            {
                GroupDA.RemoveGeneralGroupMember("administrators", adminName);
            }
            else
            {
                r.ResultType = ResultType.Error;
                r.Message = "只剩下最后一位管理员，不允许删除。";
            }
            return r;

        }

        public static void AddAdministrator(string adminName)
        {
            GroupDA.InsertGeneralGroupMember("administrators", adminName);
        }
    }
}
